/************************************************************************/
/*    Author: Scott Bevin                                               */
/************************************************************************/


#include "GameSettings.h"

#include "Utilities.h"
#include "ScriptParser.h"
#include <iosfwd>
#include "Logger.h"
#include "../XPropertys/PropertyFactory.h"

namespace XF
{
	GameSettings* GameSettings::smInstance = NULL;

	GameSettings::~GameSettings()
	{
	}

	GameSettings* GameSettings::Instance()
	{
		assert(smInstance);

		return smInstance;
	}

	void GameSettings::Initialise(std::string fileName)
	{
		assert(!smInstance);

		SSELOG << "Loading game settings file: " << fileName;

		smInstance = new GameSettings();
		smInstance->mFileName = fileName;

		XF::ScriptParser fileParser;

		if(!fileParser.ParseFile(fileName, 
			XF::ScriptParser::ConfigScriptCallback::FromMethod<GameSettings, &GameSettings::FileParserCallback>(smInstance)))
		{
			SSELOG << "Failed to load settings file";

			smInstance = NULL;
		}
		else
			SSELOG << "Finished loading settings";
	}

	void GameSettings::FileParserCallback(std::string key, std::vector<std::string> &arguments)
	{
		IProperty* newProp = PropertyFactory::CreateProperty(key, arguments[0]);

		std::string value = "";

		for(unsigned int i = 1; i < arguments.size(); ++i) value += arguments[i] + " ";
		value = value.substr(0, value.size() - 1);

		newProp->SetFromString(value);

		smInstance->AddProperty(newProp);

		ILOG << "Game setting loaded: (" << key << ") " << arguments[0] << ": " << value;
	}

	void GameSettings::ShutDown()
	{
		assert(smInstance);

		GameSettings::SaveSettings();

		delete smInstance;
		smInstance = NULL;
	}

	void GameSettings::SaveSettings()
	{
		std::fstream file;

		ILOG << "Saving game settings";

		file.open(smInstance->mFileName.c_str(), std::ios_base::out);

		if(file.is_open())
		{
			for(std::map<std::string, IProperty*>::iterator it = smInstance->mProperties.begin();
				it != smInstance->mProperties.end(); ++it)
			{
				std::string type = it->second->TypeID();
				std::string name = it->second->Name();
				std::string value = it->second->ToString();

				file << type << " " << name << " " << value << ";\n";

				ILOG << "Game setting saved: (" << type << ") " << name << ": " << value;
			}
		}

		ILOG << "Finished saving game settings";
	}
}